<!--
 * @description 福利创建-人员设置
 * @author dumeng
 * @date 2021/7/30
 -->
<template>
  <div class="insert-person-page">
    <div class="page-title">
      <span class="title">人员设置</span>
      <div class="btns">
        <el-button type="primary" @click="showuser = true">添加人员</el-button>
        <el-button type="primary" style="margin-left: 10px" @click="handleDownload">下载批量导入模版</el-button>
        <el-button type="primary" style="margin-left: 10px" @click="handleUpload">批量导入</el-button>
      </div>

    </div>
    <div class="page-main">
      <div v-if="isSetPerson === false" class="no-data">
        <img src="../../images/nodata.png" alt="">
        <div class="tip">当前人员列表为空</div>
        <el-button type="primary" plain @click="showuser = true">添加人员</el-button>
      </div>
      <section v-else class="user-main">
        <section class="main-search separate">
          <section class="search-inner">
            <el-row>
              <el-col :span="8">
                <section class="search-inner-item">
                  <div class="item-label">姓名</div>
                  <el-input
                    v-model.trim="search.userRealname"
                    style="width: 90%"
                    class="filter-item"
                    placeholder="请输入姓名搜索"
                  />
                </section>
              </el-col>
              <el-col :span="8">
                <section class="search-inner-item">
                  <div class="item-label">联系电话</div>
                  <el-input
                    v-model.trim="search.phoneNumber"
                    style="width: 90%"
                    class="filter-item"
                    placeholder="请输入联系电话搜索"
                  />
                </section>
              </el-col>
              <el-col :span="8" class="search-btn">
                <el-button type="primary" @click="handleFilter">搜索</el-button>
                <el-button type="primary" @click="handleReset">重置</el-button>
              </el-col>
            </el-row>
          </section>
        </section>
        <section class="main-table">
          <v-table
            :selection="false"
            :list="list"
            tag="grantuser"
            :list-loading="loading"
            :filter-column="filtercolumn"
          >
            <el-table-column align="center" label="操作">
              <template slot-scope="{ row }">
                <el-button type="text" size="mini" @click="handleDelete(row.id)">删除</el-button>
              </template>
            </el-table-column>
          </v-table>
          <pagination
            v-if="total > 0"
            :total="total"
            :page.sync="listQuery.page"
            :limit.sync="listQuery.limit"
            @pagination="getList"
          />
        </section>
      </section>
      <div class="page-btns" :class="[total && 'mt20']">
        <el-button v-if="type === '0' && range !== '2'" type="primary" @click="nextStep">{{
          total === 0 ? '没想好，先设置专区/商品' : '确定并进入商品设置'
        }}
        </el-button>
        <el-button v-else type="primary" @click="finish">配置完成</el-button>
        <el-button plain @click="$emit('setStep', 0)">上一步</el-button>
      </div>
    </div>
    <v-user v-if="showuser" :id="id" :type="type" @comit="handleUserComit" @cancel="showuser = false" />
    <!-- 发布时的弹窗 -->
    <el-dialog
      v-el-drag-dialog
      title="提示"
      custom-class="sendDialog"
      :show-close="false"
      :visible.sync="sendVisible"
      width="550px"
      :destroy-on-close="true"
      :close-on-click-modal="false"
    >
      <div class="s-top">
        <div class="top-items">
          <div class="t-item">
            <div class="num">{{ chooseItem.issueCoinTotal || '0' }}</div>
            <div class="text">
              <span v-if="chooseItem.classifType==='0' || chooseItem.classifType==='2' || chooseItem.classifType==='8'">发放总金额</span>
              <span v-if="chooseItem.classifType==='1' || chooseItem.classifType==='7' ">发放总张数</span>
            </div>
          </div>
          <div class="t-item">
            <div class="num">{{ chooseItem.issuePersonnelTotal || '0' }}</div>
            <div class="text">发放总人数</div>
          </div>
        </div>
        <div v-if="chooseItem.alreadyList && chooseItem.alreadyList.length>0" class="top-list">
          <div v-for="(item,i) in chooseItem.alreadyList" :key="i" class="list-item">
            <div class="item-item"><span class="item-text">红包金额（每人）： </span> {{ item.issueCoinTotal || '0' }}</div>
            <div class="item-item"> <span class="item-text">红包人数（人）：</span> {{ item.issuePersonnelTotal || '0' }}</div>
          </div>
        </div>
      </div>
      <div class="s-bottom">
        <div class="b-item">
          <div class="name">福利名称：</div>
          <div class="value">{{ chooseItem.giveName || '' }}</div>
        </div>
        <div class="b-item">
          <div class="name">福利领取起止时间：</div>
          <div class="value">{{
            (chooseItem['receiveStarttime'] && chooseItem['receiveStarttime']) + '至' + (
              chooseItem['receiveEndtime'] && chooseItem['receiveEndtime']) || ''
          }}
          </div>
        </div>
        <div class="b-item">
          <div class="name">福利使用起止时间：</div>
          <div class="value">{{
            (chooseItem['expirationStartdate'] && chooseItem['expirationStartdate']) + '至' + (
              chooseItem['expirationDate'] && chooseItem['expirationDate']) || ''
          }}
          </div>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handlePublish('')">不发布</el-button>
        <el-button
          style="background-color: #EB523C;color:#fff;"
          @click="handlePublish('GIPSTSTUS01')"
        >发布并发放所有人员</el-button>
      </span>
    </el-dialog>
    <!--批量导入-->
    <v-upload v-if="showupload" :id="id" @success="handleUploadSuccess" @cancel="handleUploadCancel" />
  </div>
</template>

<script>

import { del, insert, queryPage } from './api'
import CryptoJS from '@/utils/aesJiaJM'
import Pagination from '@/components/Pagination'
import VTable from '@/components/Table'
import VUser from '../user'
import { getWelfareActivityView, updatePublish } from '../../api'
import elDragDialog from '@/directive/el-drag-dialog'
import { exportSign } from '@/utils/fileImportOrExportSign' // base on element-ui
import VUpload from '../upload'
export default {
  name: 'InsertPerson',
  components: { VUpload, VUser, Pagination, VTable },
  directives: { elDragDialog },
  props: {
    type: {
      type: String,
      default: ''
    },
    id: {
      type: String,
      default: ''
    },
    range: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      search: {
        userRealname: '',
        phoneNumber: ''
      },
      list: [],
      listQuery: {
        page: 1,
        limit: 10
      },
      total: 0,
      loading: false,
      showuser: false,
      sendVisible: false,
      chooseItem: {},
      isSetPerson: false, // 是否添加过人员
      showupload: false
    }
  },
  created() {
    this.getList()
  },
  methods: {
    handleDownload() {
      const link = document.createElement('a')
      link.style.display = 'none'
      link.href = '/API-ENTERPRISE-BACKEND/backend/giveInfoDetail/downloadGiveInfoDetailTemplate' + exportSign().paramStr
      link.setAttribute('download', '模版.xls')
      link.setAttribute('target', '_blank')
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
    },

    handleUpload() {
      this.showupload = true
    },

    handleUploadCancel() {
      this.showupload = false
    },

    handleUploadSuccess() {
      this.getList()
    },
    finish() {
      if (this.isSetPerson === false) {
        this.$confirm('还未设置人员, 是否继续?', '提示', {
          confirmButtonText: '暂不设置',
          cancelButtonText: '去设置',
          type: 'warning'
        }).then(() => {
          this.getWelfareActivityView()
        })
      } else {
        this.getWelfareActivityView()
      }
    },
    /**
     * 配置完成
     */
    getWelfareActivityView() {
      const loading = this.$loading({
        lock: true,
        text: '请稍后',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.3)'
      })
      return new Promise((resolve, reject) => {
        getWelfareActivityView({ id: this.id }).then(res => {
          loading.close()
          this.chooseItem = res.data.data || {}
          this.sendVisible = true
        }).catch(error => {
          loading.close()
          reject(error)
        })
      })
    },
    handlePublish(status) {
      if (status) {
        const loading = this.$loading({
          lock: true,
          text: '请稍后',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.3)'
        })
        return new Promise((resolve, reject) => {
          updatePublish({ id: this.id, publishStatus: status }).then(res => {
            loading.close()
            this.$message({
              title: '成功',
              message: '配置成功',
              type: 'success',
              duration: 2000,
              onClose: () => {
                this.$router.push({
                  path: this.$filterPath('index'),
                  query: { t: this.$route.query.t }
                })
              }
            })
          }).catch(error => {
            loading.close()
            reject(error)
          })
        })
      } else {
        this.$router.push({
          path: this.$filterPath('index'),
          query: { t: this.$route.query.t }
        })
      }
    },
    /**
     * 下一步
     */
    nextStep() {
      this.$emit('setStep', 2)
      this.$emit('isSetPerson', this.total > 0)
    },
    handleUserComit({ data, number }) {
      if (data && data.length > 0) {
        const list = []
        data.forEach(a => {
          list.push(a.id)
        })
        const loading = this.$loading({
          lock: true,
          text: '请稍后',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.3)'
        })
        return new Promise((resolve, reject) => {
          insert({
            userIds: list.join(','),
            giveId: this.id,
            giveNumber: number
          }).then(() => {
            loading.close()
            this.dialogFormVisible = false
            this.$message({
              title: '成功',
              message: '添加成功',
              type: 'success',
              duration: 2000
            })
            this.showuser = false
            this.getList()
          }).catch(error => {
            reject(error)
            loading.close()
          })
        })
      }
    },
    getList(obj) {
      this.loading = true
      var query = {
        giveId: this.id,
        queryFlag: 0,
        page: obj ? obj.page : this.listQuery.page,
        pageSize: obj ? obj.limit : this.listQuery.limit,
        status: this.active === 'all' ? '' : this.active,
        userRealname: this.search.userRealname,
        phoneNumber: CryptoJS.$aesJiaM(this.search.phoneNumber)
      }
      return new Promise((resolve, reject) => {
        queryPage(query).then(({ data }) => {
          const list = data.data.rows
          if (list && list.length > 0) {
            this.list = list.map(a => {
              return {
                ...a,
                number: a.giveNumber,
                JPhoneNumber: a.phoneNumber,
                edit: false
              }
            })
          } else {
            this.list = []
          }
          this.total = data.data.total
          this.isSetPerson = !(query.userRealname === '' && query.phoneNumber === '' && query.page === 1 && !this.total)
          // console.log("list",this.list)
          this.loading = false
        }).catch(error => {
          reject(error)
          this.loading = false
        })
      })
    },
    filtercolumn(scope, item) {
      if (item === 'userStatus') {
        return scope.row[item] || '--'
      } else if (item === 'isDirectional') {
        return scope.row[item] === 'ZPID02' ? '否' : '是'
      } else if (item === 'userIdnumber') {
        return CryptoJS.$aesJieM(scope.row[item]) || '--'
      } else if (item === 'phoneNumber') {
        return CryptoJS.$aesJieM(scope.row[item]) || '--'
      } else {
        return scope.row[item] || '--'
      }
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleReset() {
      this.listQuery.page = 1
      for (const i in this.search) {
        this.search['' + i + ''] = ''
      }
      this.getList()
    },
    handleDelete(ids) {
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        return new Promise((resolve, reject) => {
          del(ids).then(() => {
            this.$message({
              title: '成功',
              message: '删除成功',
              type: 'success',
              duration: 2000
            })
            this.getList()
          }).catch(error => {
            reject(error)
          })
        })
      }).catch(() => {
      })
    }
  }
}
</script>

<style lang="scss">
.insert-person-page {
  background-color: #fff;
  min-height: calc(100vh - 140px);

  .page-title {
    height: 60px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 20px;
    border-bottom: 1px solid #e5e5e5;

    .title {
      font-size: 16px;
      font-weight: bold;
    }
    .btns{
      display: flex;
    }
  }

  .page-main {
    .no-data {
      text-align: center;
      margin: 50px 0;

      img {
        width: 200px;
        height: 200px;
      }

      .tip {
        color: #666;
        margin: 20px 0;
        font-size: 14px;
      }
    }

    .page-btns {
      margin-top: 80px;
      text-align: center;
      margin-bottom: 20px;

      &.mt20 {
        margin-top: 20px;
      }
    }

    .user-main {
      .main-search {
        background-color: #fff;
        padding: 0 10px;

        &.separate {
          .search-inner {
            padding-top: 10px;

            .search-inner-item {
              .item-label {
                height: 30px;
                line-height: 30px;
                font-size: 14px;
                color: #a6a6a6;
                font-weight: 400;
              }

              .el-input {
                position: relative;

                &.el-date-editor input {
                  padding-left: 30px;
                }

                .el-input__inner {
                  border: none;
                  padding: 0;
                }

                &:after {
                  content: "";
                  height: 1px;
                  background-color: #e2e3e8;
                  position: absolute;
                  left: 0;
                  right: 0;
                  bottom: 0;
                }
              }
            }
          }

          .search-btn {
            height: 66px;
            display: flex;
            align-items: flex-end;
          }
        }
      }

      .main-buttons {
        display: flex;
        line-height: 36px;
        margin-top: 10px;

        .main-buttons-title {
          flex: 1;
          height: 36px;
          line-height: 36px;
          font-size: 16px;
          font-weight: bold;
          color: rgba(51, 51, 51, 1);
        }
      }

      .main-table {
        .table-search {
          margin-bottom: 10px;
        }

        .edit-input {
          padding-right: 40px;
        }

        .cancel-btn {
          position: absolute;
          right: 15px;
          top: 10px;
        }
      }
    }
  }

  .sendDialog{
    .s-top{
      margin: 19px auto 0;
      width: 500px;
      opacity: 1;
      background: linear-gradient(#f25a44 0%, #ef7e46 99%);
      border-radius: 8px ;
      padding-bottom: 5px;
      .top-items{
        height: 74px;
        display: flex;
        justify-content: space-between;
        .t-item{
          height: 100%;
          flex: 1;
          color: #ffffff;
          text-align: center;
          padding-top: 21px;
          .num{
            font-size: 16px;
            font-family: PingFang SC Medium, PingFang SC Medium-Medium;
            font-weight: 500;
          }
          .text{
            margin-top: 5px;
            font-size: 14px;
            font-family: PingFang SC Regular, PingFang SC Regular-Regular;
            font-weight: 400;
          }
        }
      }
      .top-list{
        width: 450px;
        margin: 0 auto 5px auto;
        background: linear-gradient(0deg,#ffffff 0%, #ffffff 92%, #fc9c7e 100%);
        border-top: 6px solid #D8431B;
        opacity: 0.4, filter alpha(opacity=50);
        min-height: 55px;
        border-radius: 0 0 6px 6px;
        padding: 0 20px;
        position: relative;
        &:after{
          position: absolute;
          top: -6px;
          left: -10px;
          content: '';
          height: 12px;
          width: 10px;
          background: #D8431B;
          border-radius: 16px 0 0 16px;
        }
        &:before{
          position: absolute;
          top: -6px;
          right: -10px;
          content: '';
          height: 12px;
          width: 10px;
          background: #D8431B;
          border-radius: 0 16px  16px  0;
        }
        .list-item{
          height: 55px;
          display: flex;
          justify-content: space-between;
          color: #fff;
          border-bottom: 1px solid #eeeeee;
          box-sizing: border-box;
          &:last-child{
            border: none;
          }
          .item-item{
            display: flex;
            justify-content: center;
            align-items: center;
            flex: 1;
            font-size: 14px;
            font-family: PingFang SC Regular, PingFang SC Regular-Regular;
            font-weight: 400;
            color: #333333;
            .item-text{
              color: #999999;
            }
          }
        }
      }
    }
    .s-bottom{
      margin: 0 auto 19px;
      width: 500px;
      height: 142px;
      opacity: 1;
      display: flex;
      flex-direction: column;
      .b-item{
        flex: 1;
        display: flex;
        align-items: center;
        font-size: 14px;
        font-family: PingFang SC Regular, PingFang SC Regular-Regular;
        font-weight: 400;
        border-bottom: 1px solid #eee;
        &:last-child{
          border: none;
        }
        .name{
          color: #999999;
        }
        .value{
          color: #333;
          font-weight: bold;
        }
      }
    }
    .el-dialog__footer{
      text-align: center !important;
    }
  }

}
</style>
